using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Web;
using System.Xml.Serialization;
namespace Net35.Xrm.Sdk.Client
{
	[SecuritySafeCritical]
	[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
	internal sealed class IdentityProviderLookup
	{
		private const string OrgIdIdentityService = "{0}/GetUserRealm.srf";
		private const string OrgIdIdentityQuery = "login={0}&xml=1";
		private static IdentityProviderLookup _instance;
		private readonly IdentityProviderDictionary _identityProviderDictionary = new IdentityProviderDictionary();
		public static IdentityProviderLookup Instance
		{
			get
			{
				IdentityProviderLookup arg_14_0;
				if ((arg_14_0 = IdentityProviderLookup._instance) == null)
				{
					arg_14_0 = (IdentityProviderLookup._instance = new IdentityProviderLookup());
				}
				return arg_14_0;
			}
		}
		internal IdentityProviderDictionary IdentityProviderDictionary
		{
			get
			{
				return this._identityProviderDictionary;
			}
		}
		public static void Clear()
		{
			IdentityProviderLookup._instance = null;
		}
		public IdentityProvider GetIdentityProvider(System.Uri host, System.Uri orgIdServiceRoot, string userPrincipalName)
		{
			ClientExceptionHelper.ThrowIfNull(host, "host");
			ClientExceptionHelper.ThrowIfNull(orgIdServiceRoot, "orgIdServiceRoot");
			ClientExceptionHelper.ThrowIfNullOrEmpty(userPrincipalName, "userPrincipalName");
			if (this.IdentityProviderDictionary.ContainsKey(userPrincipalName))
			{
				return this.IdentityProviderDictionary[userPrincipalName];
			}
			string text = string.Format(CultureInfo.InvariantCulture, "login={0}&xml=1", new object[]
			{
				HttpUtility.UrlEncode(userPrincipalName)
			});
			string text2 = host.AbsoluteUri.TrimEnd(new char[]
			{
				'/'
			});
			string uriString = string.Format(CultureInfo.InvariantCulture, "{0}/GetUserRealm.srf", new object[]
			{
				text2
			});
			try
			{
				System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(uriString));
				httpWebRequest.Method = "POST";
				httpWebRequest.ContentLength = (long)text.Length;
				httpWebRequest.ContentType = "application/x-www-form-urlencoded";
				RealmInfo realmInfo = null;
				using (Stream requestStream = httpWebRequest.GetRequestStream())
				{
					byte[] bytes = Encoding.UTF8.GetBytes(text);
					requestStream.Write(bytes, 0, text.Length);
				}
				using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse())
				{
					using (Stream responseStream = httpWebResponse.GetResponseStream())
					{
						using (StreamReader streamReader = new StreamReader(responseStream))
						{
							System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(RealmInfo));
							realmInfo = (xmlSerializer.Deserialize(streamReader) as RealmInfo);
						}
					}
				}
				if (realmInfo != null)
				{
					IdentityProvider identityProvider = IdentityProviderLookup.ExtractIdentityProvider(orgIdServiceRoot, realmInfo);
					this.IdentityProviderDictionary[userPrincipalName] = identityProvider;
					return identityProvider;
				}
			}
			catch (System.Net.WebException)
			{
			}
			return null;
		}
		private static IdentityProvider ExtractIdentityProvider(System.Uri orgIdServiceRoot, RealmInfo realmInfo)
		{
			IdentityProvider result = null;
			string namespaceType = realmInfo.NamespaceType;
			if (!string.IsNullOrEmpty(namespaceType))
			{
				if (string.Compare(namespaceType, "Managed", StringComparison.OrdinalIgnoreCase) == 0)
				{
					result = new OnlineIdentityProvider
					{
						IdentityProviderType = IdentityProviderType.OrgId,
						ServiceUrl = orgIdServiceRoot
					};
				}
				else if (string.Compare(namespaceType, "Federated", StringComparison.OrdinalIgnoreCase) == 0)
				{
					if (string.IsNullOrEmpty(realmInfo.MetadataUrl))
					{
						result = new OnlineIdentityProvider
						{
							IdentityProviderType = IdentityProviderType.LiveId,
							ServiceUrl = new System.Uri(realmInfo.TokenServiceAuthenticationUrl)
						};
					}
					else
					{
						result = new LocalIdentityProvider
						{
							IdentityProviderType = IdentityProviderType.ADFS,
							ServiceUrl = new System.Uri(realmInfo.MetadataUrl)
						};
					}
				}
			}
			return result;
		}
	}
}
